var express = require('express')
var router = express.Router()
var connection = require('../db/sql.js')
var user = require('../db/userSql.js')
var QcloudSms = require("qcloudsms_js")
//引入token包
let jwt = require('jsonwebtoken')
//引入支付宝配置文件
const alipaySdk = require('../db/alipay.js')
const AlipayFormData = require('alipay-sdk/lib/form').default
//引入axios
const axios = require('axios')
//判断token有没有过期，过期返回true
function getTimeToken (exp) {
  let getTime = parseInt(new Date().getTime() / 1000) //毫秒转秒
  console.log(getTime, exp)
  console.log(getTime - exp)

  if (getTime - exp > 0) {
    return true
  }
}

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' })
})

//修改订单的支付状态由2改为3，待支付=》已支付
router.post('/api/successPayment', function (req, res, next) {
  //token
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  //订单号
  let out_trade_no = req.body.out_trade_no
  let trade_no = req.body.trade_no
  //支付宝配置

  //开始对接支付宝API
  const formData = new AlipayFormData()
  //调用setMethod()并传入get。会返回可以跳转的支付页面的 url
  formData.setMethod('get')
  //支付时的信息
  formData.addField('bizContent', {
    out_trade_no,
    trade_no,
  })
  //返回promise
  const result = alipaySdk.exec(
    'alipay.trade.query',
    {},
    { formData: formData },
  )

  //后端请求支付宝
  result.then(resData => {
    axios({
      method: 'GET',
      url: resData
    }).then(data => {
      let responseCode = data.data.alipay_trade_query_response
      if (responseCode.code == '10000') {
        switch (responseCode.trade_status) {
          case 'WAIT_BUYER_PAY':
            res.send({
              data: {
                code: 0,
                data: {
                  msg: '支付宝有交易记录，没付款'
                }
              }
            })
            break

          case 'TRADE_CLOSED':
            res.send({
              data: {
                code: 1,
                data: {
                  msg: '交易关闭'
                }
              }
            })
            break

          case 'TRADE_FINISHED':
            connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
              //用户id
              let uId = results[0].id
              connection.query(`select * from store_order where uId = ${uId} and order_id = ${out_trade_no}`, function (err, result) {
                let id = result[0].id
                //订单的状态修改掉2==》3
                connection.query(`update store_order set order_status = replace(order_status,'2','3') where id = ${id}`, function () {
                  res.send({
                    data: {
                      code: 2,
                      data: {
                        msg: '交易完成'
                      }
                    }
                  })
                })
              })
            })
            break

          case 'TRADE_SUCCESS':
            connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
              //用户id
              let uId = results[0].id
              connection.query(`select * from store_order where uId = ${uId} and order_id = ${out_trade_no}`, function (err, result) {
                let id = result[0].id
                //订单的状态修改掉2==》3
                connection.query(`update store_order set order_status = replace(order_status,'2','3') where id = ${id}`, function () {
                  res.send({
                    data: {
                      code: 2,
                      data: {
                        msg: '交易完成'
                      }
                    }
                  })
                })
              })
            })
            break
        }
      } else if (responseCode.code == '40004') {
        res.send({
          data: {
            code: 4,
            msg: '交易不存在'
          }
        })
      }
    }).catch(err => {
      res.send({
        data: {
          code: 500,
          msg: '交易失败',
          err
        }
      })
    })
  })


})

//发起支付
router.post('/api/payment', (req, res, next) => {

  //订单号
  let orderId = req.body.orderId
  //商品名称
  let name = req.body.name
  //商品总价
  let price = req.body.price


  //开始对接支付宝API
  const formData = new AlipayFormData()
  //调用setMethod()并传入get。会返回可以跳转的支付页面的 url
  formData.setMethod('get')

  //支付时的信息
  formData.addField('bizContent', {
    outTradeNo: orderId,  //订单号
    productCode: 'FAST_INSTANT_TRADE_PAY',  //商品code固定写法
    totalAmount: price,  //商品总价
    subject: name,  //商品名称
  })

  //支付成功或失败跳转的链接
  formData.addField('returnUrl', 'http://localhost:8080/payment')
  //返回promise
  const result = alipaySdk.exec(
    'alipay.trade.page.pay',
    {},
    { formData: formData },
  )

  //对接支付宝成功，取得支付宝返回的数据:支付跳转的url
  result.then(resp => {
    res.send({
      data: {
        code: 200,
        success: true,
        msg: '支付中',
        paymentUrl: resp,
      }
    })
  })

})

//修改订单状态
router.post('/api/submitOrder', (req, res, next) => {
  //获取token,解析token
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  //订单号
  let orderId = req.body.orderId
  //购物车结算的商品id
  let shopArr = req.body.shopArr
  //查询订单id
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uid = results[0].id
    connection.query(`select * from store_order where uid=${uid} and order_id = ${orderId}`, function (err, r) {
      //订单id
      let id = r[0].id
      //修改订单状态
      connection.query(`update store_order set order_status = '2' where id = ${id}`, () => {
        //删除生成了订单的购物车商品
        shopArr.forEach(v => {
          connection.query(`delete from goods_cart where id = ${v}`, () => { })
        })
        res.send({
          data: {
            code: 200,
            success: true,
          }
        })

      })
    })
  })

})
//查询订单
router.post('/api/selectOrder', (req, res, next) => {
  //接受前端传过来的订单id
  let order_id = req.body.order_id
  connection.query(`select * from store_order where order_id = "${order_id}"`, (error, result) => {
    res.send({
      data: {
        success: true,
        code: 200,
        data: result,
      }
    })
  })
})

//生成订单
router.post('/api/addOrder', (req, res, next) => {
  //token
  let token = req.headers.token
  let tokenObj = jwt.decode(token)

  let goodsArr = req.body.arr
  //订order_id规则：时间戳+6位随机数
  function setTimeDateFmt (s) {
    return s < 10 ? '0' + s : s
  }
  function randomNumber () {
    const now = new Date()
    let month = now.getMonth() + 1
    let day = now.getDate()
    let hour = now.getHours()
    let minutes = now.getMinutes()
    let seconds = now.getSeconds()
    month = setTimeDateFmt(month)
    day = setTimeDateFmt(day)
    hour = setTimeDateFmt(hour)
    minutes = setTimeDateFmt(minutes)
    seconds = setTimeDateFmt(seconds)
    let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString()
    return orderCode
  }

  // 未支付：1，
  // 待支付：2，
  // 支付成功：3，
  // 支付失败：0，
  //商品列表名称
  let goodsName = []
  //商品总金额
  let goodsPrice = 0
  //商品总数量
  let goodsNum = 0
  //订单号
  let orderId = randomNumber()
  goodsArr.forEach(v => {
    goodsName.push(v.goods_name)
    goodsPrice += v.goods_price * v.goods_num
    goodsNum += v.goods_num
  })
  //根据解析到的token电话，查询当前用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uid = results[0].id
    connection.query(`insert into store_order (uid,order_id,goods_name,goods_price,goods_num,order_status) values(${uid},"${orderId}","${goodsName}",${goodsPrice},${goodsNum},"1")`, (e, r) => {
      connection.query(`select * from store_order where uid = ${uid} and order_id="${orderId}"`, function (e, r) {
        res.send({
          data: {
            code: 200,
            success: true,
            data: r,
          }
        })
      })
    })

  })
})

//删除收货地址
router.post('/api/delete_address', (req, res, next) => {
  let id = req.body.id
  connection.query(`delete from address where id = ${id}`, (error, results) => {
    res.send({
      data: {
        code: 200,
        success: true,
        msg: '删除成功',
      }
    })
  })
})

//修改用户地址
router.post('/api/update_address', (req, res, next) => {
  let { id, name, tel, areaCode, province, city, county, addressDetail, isDefault } = req.body
  //token
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  //根据解析到的token电话，查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uid = results[0].id
    //判断是否为默认地址
    if (isDefault == 1) {
      connection.query(`update address set isDefault = 0 where uid = ${uid}  and isDefault = 1`, function (err, datas) { })
      connection.query(`update address set uid=${uid},name="${name}", tel="${tel}",areaCode="${areaCode}", province="${province}",city="${city}", county="${county}", addressDetail="${addressDetail}",isDefault=${isDefault} where id=${id}`, (error, r) => {
        res.send({
          data: {
            code: 200,
            success: true,
            msg: '收货地址修改成功',
          }
        })
      })
    } else {
      connection.query(`update address set uid=${uid},name="${name}", tel="${tel}",areaCode="${areaCode}", province="${province}",city="${city}", county="${county}", addressDetail="${addressDetail}",isDefault=${isDefault} where id=${id}`, (error, r) => {
        res.send({
          data: {
            code: 200,
            success: true,
            msg: '收货地址修改成功',
          }
        })
      })
    }

  })
})


//查询用户的收货地址
router.get('/api/select_address', (req, res, next) => {
  //token
  let token = req.headers.token
  //解析token
  let tokenObj = jwt.decode(token)
  //根据解析到的token电话，查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uid = results[0].id
    connection.query(`select * from address where uid = ${uid}`, (e, r) => {
      res.send({
        data: {
          code: 200,
          success: true,
          msg: "查询成功",
          data: r,
        }
      })
    })
  })
})

//保存用户新增的地址
router.post('/api/add_address', (req, res, next) => {
  let { name, tel, areaCode, province, city, county, addressDetail, isDefault } = req.body


  //token
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  //根据解析到的token电话，查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uid = results[0].id
    //判断是否为默认地址
    if (isDefault == 1) {
      connection.query(`update address set isDefault = 0 where uid = ${uid}  and isDefault = 1`, function (err, datas) { })
      connection.query(`insert into address (uid,name, tel,areaCode, province, city, county, addressDetail, isDefault) values (${uid},"${name}","${tel}","${areaCode}","${province}","${city}","${county}","${addressDetail}",${isDefault})`, (error, r) => {
        res.send({
          data: {
            code: 200,
            success: true,
            msg: '收货地址添加成功',
          }
        })
      })
    } else {
      connection.query(`insert into address (uid,name, tel,areaCode, province, city, county, addressDetail, isDefault) values (${uid},"${name}","${tel}","${areaCode}","${province}","${city}","${county}","${addressDetail}",${isDefault})`, (error, r) => {
        res.send({
          data: {
            code: 200,
            success: true,
            msg: '收货地址添加成功',
          }
        })
      })
    }

  })
})

//更新购物车商品数量
router.post('/api/updateNum', (req, res, next) => {
  let { id, num } = req.body
  connection.query(`update goods_cart set goods_num = ${num} where id = ${id} `, (error, results) => {
    if (error) throw error
    res.send({
      data: {
        code: 200,
        success: true,
      }
    })
  })
})
//删除购物车数据
router.post('/api/deleteCart', (req, res, next) => {
  let ids = req.body.ids
  ids.forEach((id, index, ids) => {
    connection.query(`delete from goods_cart where id=${id}`, (error, results) => {
      if (error) throw error
      if (index == ids.length - 1)
        res.send({
          data: {
            code: 200,
            success: true,
            msg: '删除成功',
          }
        })
    })
  })


})

//查询购物车数据
router.get('/api/selectCart', function (req, res) {
  //token
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  //根据解析到的token电话，查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uid = results[0].id
    //查询购物车
    connection.query(`select * from goods_cart where uid = ${uid}`, function (error, results) {
      res.send({
        data: {
          code: 200,
          success: true,
          data: results
          ,
        }
      })
    })
  })
})

//添加购物车数据
router.post('/api/addCart', function (req, res, next) {
  //接收前端传的参数
  let goodsId = req.body.goodsId
  //token
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  //token过期就返回1000
  if (getTimeToken(tokenObj.exp)) {
    res.send({
      data: {
        code: 1000,
      }
    })
    return
  }

  connection.query(`select * from user where tel = ${tokenObj.tel}`, function (error, results) {
    //用户id
    let uid = results[0].id
    //查找用户添加购物车的商品信息
    connection.query(`select * from goods_list where id = ${goodsId}`, function (error, results) {
      let goodsName = results[0].name
      let goodsPrice = results[0].price
      let goodsImgUrl = results[0].imgUrl
      //判断用户之前有没有添加过该商品，有num加一，没有直接添加到goods_cart表中
      connection.query(`select * from goods_cart where uid = ${uid} and goods_id = ${goodsId}`, (error, r) => {
        if (r.length > 0) {
          let newNum = r[0].goods_num + 1
          connection.query(`update goods_cart set goods_num =${newNum} where id = ${r[0].id}`, (e, datas) => {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: '添加购物车成功',
              }
            })
          })
        } else {
          connection.query(`insert into goods_cart (uid,goods_id,goods_name,goods_price,goods_num,goods_imgUrl) values (${uid},${goodsId},"${goodsName}",${goodsPrice},1,"${goodsImgUrl}")`, function (error, results) {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: '添加购物车成功',
              }
            })
          })
        }
      })


    })

  })

})

//修改密码
router.post('/api/recovery', function (req, res, next) {
  let userPwd = req.body.pwd
  let userTel = req.body.phone
  connection.query(`update user set pwd = ${userPwd} where tel = ${userTel}`, function (error, results) {
    if (error) throw error
    res.send({
      code: 200,
      data: {
        success: true,
        msg: '修改成功'
      }
    })

  })

})

//查询用户是否存在
router.post('/api/selectUser', function (req, res, next) {
  let userData = {
    userTel: req.body.phone,
  }
  connection.query(user.queryUserTel(userData), function (error, results) {
    if (error) throw error
    //用户存在
    if (results.length > 0) {
      res.send({
        code: 200,
        data: {
          success: true,
        }
      })
    } else {
      res.send({
        code: 0,
        data: {
          success: false,
          msg: '此用户不存在',
        }
      })
    }
  })

})

//注册
router.post('/api/register', function (req, res, next) {
  let userData = {
    userTel: req.body.phone,
    userPwd: req.body.pwd,
  }
  //查询用户是否存在
  connection.query(user.queryUserTel(userData), function (error, results) {
    if (error) throw error
    //用户存在
    if (results.length > 0) {
      res.send({
        code: 200,
        data: {
          success: false,
          msg: '用户已存在！',
        }
      })
    } else {
      //不存在，新增一条用户数据
      connection.query(user.insertData(userData), function (error, results) {
        if (error) throw error
        connection.query(user.queryUserTel(userData), function (err, r) {
          res.send({
            code: 200,
            data: {
              success: true,
              msg: '注册成功',
              data: r[0],
            }
          })
        })
      })
    }
  })
})
//增加一个用户
router.post('/api/addUser', function (req, res, next) {
  let userData = {
    userTel: req.body.phone,
  }
  //查询用户是否存在
  connection.query(user.queryUserTel(userData), function (error, results) {
    if (error) throw error
    //用户存在
    if (results.length > 0) {
      res.send({
        code: 200,
        data: {
          success: true,
          msg: '登录成功',
          data: results[0]
        }
      })
    } else {
      //不存在，新增一条用户数据
      connection.query(user.insertData(userData), function (error, results) {
        if (error) throw error
        connection.query(user.queryUserTel(userData), function (err, r) {
          res.send({
            code: 200,
            data: {
              success: true,
              msg: '登录成功',
              data: r[0],
            }
          })
        })
      })
    }
  })
})

//发送手机验证码
router.post('/api/code', function (req, res, next) {
  let tel = req.body.phone

  // 短信应用SDK AppID
  var appid = 1400187558  // SDK AppID是1400开头

  // 短信应用SDK AppKey
  var appkey = "dc9dc3391896235ddc2325685047edc7"

  // 需要发送短信的手机号码
  var phoneNumbers = [tel]

  // 短信模板ID，需要在短信应用中申请
  var templateId = 285590  // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请

  // 签名
  var smsSign = "三人行慕课"  // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`

  // 实例化QcloudSms
  var qcloudsms = QcloudSms(appid, appkey)

  // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
  function callback (err, ress, resData) {
    if (err) {
      console.log("err: ", err)
    } else {
      res.send({
        code: 200,
        data: {
          success: true,
          data: ress.req.body.params[0]
        }
      })
    }
  }

  var ssender = qcloudsms.SmsSingleSender()
  //这个变量：params 就是往手机上，发送的短信
  var params = [Math.floor(Math.random() * (9999 - 1000)) + 1000]
  ssender.sendWithParam(86, phoneNumbers[0], templateId, params, smsSign, "", "", callback)  // 签名参数不能为空串
})

//登录验证
router.post('/api/login', function (req, res, next) {
  let params = {
    userTel: req.body.userTel,
    userPwd: req.body.userPwd,
  }

  //引入token包
  let jwt = require('jsonwebtoken')
  //用户信息
  let payload = { tel: params.userTel }
  //口令
  let secret = 'drinkGoodTea'
  //生成token
  let token = jwt.sign(payload, secret, { expiresIn: '24h' })

  //查询用户手机号是否存在
  connection.query(user.queryUserTel(params), function (error, results) {
    //手机号存在
    if (results.length > 0) {
      let id = results[0].id
      //验证密码是否正确
      connection.query(user.queryUserPwd(params), function (error, results) {
        if (results.length > 0) {
          connection.query(`update user set token = "${token}" where id = ${id}`, function (err, result) {
            res.send({
              code: 200,
              data: {
                success: true,
                msg: '登录成功',
                data: results[0],
              }
            })
          })
        } else {
          res.send({
            code: 302,
            data: {
              success: false,
              msg: '密码错误',
            }
          })
        }
      })
    } else {
      //不存在
      res.send({
        code: 301,
        data: {
          success: false,
          msg: '手机号不存在',
        },
      })
    }
  })
})



//大红袍数据
router.get('/api/index_list/1/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: [
      {
        id: 1,
        type: 'adList',
        data: [
          {
            id: 1,
            imgUrl: './images/dhp.jpeg',
          },
          {
            id: 2,
            imgUrl: './images/dhp.jpeg',
          },
        ]
      },
      {
        id: 2,
        type: 'likeList',
        data: [
          {
            id: 1,
            imgUrl: "./images/like.jpeg",
            name: "建盏茶具套装 红色芝麻豪 12件套",
            price: 299,
          },
          {
            id: 2,
            imgUrl: "./images/like3.jpeg",
            name: "建盏茶具套装 红色芝麻豪 12件套",
            price: 299,
          },
          {
            id: 3,
            imgUrl: "./images/like2.jpeg",
            name: "建盏茶具套装 红色芝麻豪 12件套",
            price: 299,
          },
          {
            id: 4,
            imgUrl: "./images/like3.jpeg",
            name: "建盏茶具套装 红色芝麻豪 12件套",
            price: 299,
          },
        ]
      },
    ]
  })
})

//铁观音数据
router.get('/api/index_list/2/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: [
      {
        id: 1,
        type: 'adList',
        data: [
          {
            id: 1,
            imgUrl: './images/tgy.jpeg',
          },
          {
            id: 2,
            imgUrl: './images/tgy.jpeg',
          },
        ]
      },
      {
        id: 2,
        type: 'likeList',
        data: [
          {
            id: 1,
            imgUrl: "./images/like.jpeg",
            name: "建盏茶具套装 红色芝麻豪 12件套",
            price: 299,
          },
          {
            id: 2,
            imgUrl: "./images/like3.jpeg",
            name: "建盏茶具套装 红色芝麻豪 12件套",
            price: 299,
          },
          {
            id: 3,
            imgUrl: "./images/like2.jpeg",
            name: "建盏茶具套装 红色芝麻豪 12件套",
            price: 299,
          },
          {
            id: 4,
            imgUrl: "./images/like3.jpeg",
            name: "建盏茶具套装 红色芝麻豪 12件套",
            price: 299,
          },
        ]
      },
    ]
  })
})

//推荐数据
router.get('/api/index_list/0/data/1', function (req, res, next) {
  res.send({
    code: 0,
    data: {
      topBar: [
        { id: 0, label: '推荐' },
        { id: 1, label: '大红袍' },
        { id: 2, label: '铁观音' },
        { id: 3, label: '绿茶' },
        { id: 4, label: '普洱' },
        { id: 5, label: '花茶' },
        { id: 6, label: '茶具' },
      ],
      data: [
        //这是swiper
        {
          id: 0,
          type: 'swiperList',
          data: [
            { id: 0, imgUrl: './images/swiper1.jpeg' },
            { id: 1, imgUrl: './images/swiper2.jpeg' },
            { id: 3, imgUrl: './images/swiper3.jpeg' },
          ]
        },
        //这是icons
        {
          id: 1,
          type: 'iconsList',
          data: [
            {
              id: 1,
              title: "自饮茶",
              imgUrl: "./images/icons1.png",
            },
            {
              id: 2,
              title: "茶具",
              imgUrl: "./images/icons2.png",
            },
            {
              id: 3,
              title: "茶礼盒",
              imgUrl: "./images/icons3.png",
            },
            {
              id: 4,
              title: "领福利",
              imgUrl: "./images/icons4.png",
            },
            {
              id: 5,
              title: "官方验证",
              imgUrl: "./images/icons5.png",
            },
          ]
        },
        //这是爆款推荐
        {
          id: 3,
          type: 'recommendList',
          data: [
            {
              id: 1,
              name: "龙井一号铁罐250g",
              content: "鲜爽甘醇 口粮首选",
              price: "68",
              imgUrl: "./images/recommend.jpeg",
            },
            {
              id: 2,
              name: "龙井一号铁罐250g",
              content: "鲜爽甘醇 口粮首选",
              price: "68",
              imgUrl: "./images/recommend.jpeg",
            },
          ]
        },
        //这是猜你喜欢
        {
          id: 4,
          type: 'likeList',
          data: [
            {
              id: 1,
              imgUrl: "/images/goods1.jpg",
              name: "赛事茶-第三届武夷山茶叶交易会茶鲜杯-优质茶叶160g",
              price: 238,
            },
            {
              id: 2,
              imgUrl: "/images/goods2.jpg",
              name: "茶具-中式陶瓷茶具",
              price: 46,
            },
            {
              id: 3,
              imgUrl: "/images/goods3.jpg",
              name: "绿茶-远致龙井3号",
              price: 138,
            },
            {
              id: 4,
              imgUrl: "/images/goods4.jpg",
              name: "明前春茶 绿茶 龙井",
              price: 89,
            },
            {
              id: 5,
              imgUrl: "./images/like.jpeg",
              name: "建盏茶具套装 红色芝麻豪 12件套",
              price: 299,
            },
            {
              id: 6,
              imgUrl: "./images/like.jpeg",
              name: "建盏茶具套装 红色芝麻豪 12件套",
              price: 299,
            },
            {
              id: 7,
              imgUrl: "./images/like.jpeg",
              name: "建盏茶具套装 红色芝麻豪 12件套",
              price: 299,
            },
            {
              id: 8,
              imgUrl: "./images/like.jpeg",
              name: "建盏茶具套装 红色芝麻豪 12件套",
              price: 299,
            },
            {
              id: 9,
              imgUrl: "./images/like3.jpeg",
              name: "建盏茶具套装 红色芝麻豪 12件套",
              price: 299,
            },
            {
              id: 10,
              imgUrl: "./images/like2.jpeg",
              name: "建盏茶具套装 红色芝麻豪 12件套",
              price: 299,
            },
            {
              id: 11,
              imgUrl: "./images/like3.jpeg",
              name: "建盏茶具套装 红色芝麻豪 12件套",
              price: 299,
            },
            {
              id: 12,
              imgUrl: "./images/like3.jpeg",
              name: "建盏茶具套装 红色芝麻豪 12件套",
              price: 299,
            },
          ]
        },
      ]
    }
  })
})

//查询detail页面的商品数据接口
router.get('/api/goods/id', function (req, res, next) {
  let id = req.query.id
  connection.query('select * from goods_list where id=' + id + '', function (error, results) {
    if (error) throw error
    res.json({
      code: 0,
      data: results[0],
    })
  })
})

//查询商品数据接口
router.get('/api/goods/shopList', function (req, res, next) {
  let [searchName, orderName] = Object.keys(req.query)
  let [name, order] = Object.values(req.query)
  console.log(searchName, orderName, name, order)
  connection.query('select * from goods_list where `name` like "%' + name + '%" order by ' + orderName + ' ' + order + '', function (error, results) {
    if (error) throw error
    res.send({
      code: 0,
      data: results,
    })
  })
})

//分类的数据接口
router.get('/api/goods/list', function (req, res, next) {
  res.send({
    code: 0,
    data: [
      {
        //一级
        id: 0,
        name: '推荐',
        //二级
        data: [{
          id: 0,
          name: '推荐',
          //三级
          list: [
            {
              id: 0,
              name: '铁观音',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 1,
              name: '功夫茶具',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 2,
              name: '茶具电器',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 3,
              name: '紫砂壶',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 4,
              name: '龙井',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 5,
              name: '武夷岩茶',
              imgUrl: '/images/list1.jpeg',
            },
          ]
        },
        ]
      },
      {
        //一级
        id: 1,
        name: '绿茶',
        //二级
        data: [{
          id: 0,
          name: '绿茶',
          //三级
          list: [
            {
              id: 0,
              name: '龙井',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 1,
              name: '碧螺春',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 2,
              name: '雀舌',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 3,
              name: '安吉白茶',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 4,
              name: '六安瓜片',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 5,
              name: '武夷岩茶',
              imgUrl: '/images/list1.jpeg',
            },
          ]
        },
        ]
      },
      {
        //一级
        id: 2,
        name: '红茶',
        //二级
        data: [{
          id: 0,
          name: '红茶',
          //三级
          list: [
            {
              id: 0,
              name: '龙井',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 1,
              name: '碧螺春',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 2,
              name: '雀舌',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 3,
              name: '安吉白茶',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 4,
              name: '六安瓜片',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 5,
              name: '武夷岩茶',
              imgUrl: '/images/list1.jpeg',
            },
          ]
        },
        ]
      },
      {
        //一级
        id: 3,
        name: '绿茶',
        //二级
        data: [{
          id: 0,
          name: '绿茶',
          //三级
          list: [
            {
              id: 0,
              name: '龙井',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 1,
              name: '碧螺春',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 2,
              name: '雀舌',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 3,
              name: '安吉白茶',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 4,
              name: '六安瓜片',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 5,
              name: '武夷岩茶',
              imgUrl: '/images/list1.jpeg',
            },
          ]
        },
        ]
      },
      {
        //一级
        id: 4,
        name: '白茶',
        //二级
        data: [{
          id: 0,
          name: '白茶',
          //三级
          list: [
            {
              id: 0,
              name: '龙井',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 1,
              name: '碧螺春',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 2,
              name: '雀舌',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 3,
              name: '安吉白茶',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 4,
              name: '六安瓜片',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 5,
              name: '武夷岩茶',
              imgUrl: '/images/list1.jpeg',
            },
          ]
        },
        ]
      },
      {
        //一级
        id: 5,
        name: '龙井',
        //二级
        data: [{
          id: 0,
          name: '龙井',
          //三级
          list: [
            {
              id: 0,
              name: '龙井',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 1,
              name: '碧螺春',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 2,
              name: '雀舌',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 3,
              name: '安吉白茶',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 4,
              name: '六安瓜片',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 5,
              name: '武夷岩茶',
              imgUrl: '/images/list1.jpeg',
            },
          ]
        },
        ]
      },
      {
        //一级
        id: 6,
        name: '普洱',
        //二级
        data: [{
          id: 0,
          name: '普洱',
          //三级
          list: [
            {
              id: 0,
              name: '龙井',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 1,
              name: '碧螺春',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 2,
              name: '雀舌',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 3,
              name: '安吉白茶',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 4,
              name: '六安瓜片',
              imgUrl: '/images/list1.jpeg',
            },
            {
              id: 5,
              name: '武夷岩茶',
              imgUrl: '/images/list1.jpeg',
            },
          ]
        },
        ]
      },
    ]
  })
})

module.exports = router;



